package sk.vrto.service.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import sun.misc.*;

/**
 * More robust implementation that adds salt to the AES encrypted string.
 */
public class SaltedAESStringEncrypter implements StringEncrypter {

    private static final String ALGORITHM = "AES";
    private static final byte[] KEY_VALUE =
            { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
    private static final int ITERATIONS = 2;

    private final String salt;
    private final SaltGenerator saltGenerator;

    public SaltedAESStringEncrypter(SaltGenerator saltGenerator) {
        this.saltGenerator = saltGenerator;
        salt = saltGenerator.nextSalt();
    }

    @Override
    public String encrypt(String plain) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);

            String valueToEnc;
            String eValue = plain;
            for (int i = 0; i < ITERATIONS; i++) {
                valueToEnc = salt + eValue;
                byte[] encValue = c.doFinal(valueToEnc.getBytes());
                eValue = new BASE64Encoder().encode(encValue);
            }
            return eValue;
        } catch (Exception e) {
            throw new CryptoException(e);
        }
    }

    @Override
    public String decrypt(String encrypted) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);

            String dValue = null;
            String valueToDecrypt = encrypted;
            for (int i = 0; i < ITERATIONS; i++) {
                byte[] decordedValue = new BASE64Decoder().decodeBuffer(valueToDecrypt);
                byte[] decValue = c.doFinal(decordedValue);
                dValue = new String(decValue).substring(salt.length());
                valueToDecrypt = dValue;
            }
            return dValue;
        } catch (Exception e) {
            throw new CryptoException(e);
        }
    }

    private Key generateKey() throws Exception {
        return new SecretKeySpec(KEY_VALUE, ALGORITHM);
    }

}
